from openai import OpenAI  
import os

# 必填：从服务管控页面获取对应服务的APIKey和API Base
api_key = os.getenv('spark_api')
api_base = "http://maas-api.cn-huabei-1.xf-yun.com/v1"

client = OpenAI(api_key=api_key, base_url=api_base)

def interactive_chat(model_id, initial_message=None):
    """
    交互式多轮对话函数
    
    :param model_id: 要调用的模型ID
    :param initial_message: 可选的初始消息
    """
    messages = []
    
    if initial_message:
        messages.append({"role": "user", "content": initial_message})
        print(f"用户: {initial_message}")
    
    while True:
        try:
            # 获取AI回复
            response = client.chat.completions.create(
                model=model_id,
                messages=messages,
                stream=False,
                temperature=0.7,
                max_tokens=4096,
                extra_headers={"lora_id": "0"}
            )
            
            ai_response = response.choices[0].message.content
            print(f"\nAI: {ai_response}")
            
            # 将AI回复加入对话历史
            messages.append({"role": "assistant", "content": ai_response})
            
            # 获取用户输入
            user_input = input("\n你: ")
            if user_input.lower() in ['退出', 'exit', 'quit', 'q', '再见']:
                print("对话结束，再见！")
                break
                
            messages.append({"role": "user", "content": user_input})
            
        except Exception as e:
            print(f"请求出错: {e}")
            break

if __name__ == "__main__":
    model_id = "xop3qwen1b7"  # 必填：从服务管控获取要访问服务的modelID
    
    print("********* 交互式多轮对话 *********")
    print("输入您的消息开始对话，输入'退出'、'exit'或'quit'结束对话\n")
    
    # 可选：设置初始消息
    initial_message = "你好，请介绍一下自己。"
    interactive_chat(model_id, initial_message)
    
    # 或者完全由用户开始对话
    # interactive_chat(model_id)